<template>
	<el-main v-if="isAlready" style="text-align: center;padding-left: 0px;padding-right: 0px;">
		<el-card class="documentall" style="border-radius: 7px;">
			<template #header>
				<div style="padding: 0 0px 5px 0px;height: 70px;margin-bottom: 0px;margin-right: 0px;margin-bottom: -10px;">
					<div class="documentheader" style="text-align: center;margin-bottom: -20px;">
						<span style="color: #434343;font-size: 16pt;font-weight: 400;">
							{{form.name||configName}}
						</span>
					</div>
					<div style="float: right;margin-right:10px;margin-top: -20px;">
						<template v-if="form._submitFlag">
							<el-button link plain type="primary" @click="saveDocument" :loading="loading" style="float: left;margin-right: 5px;">保存</el-button>
							<template v-if="form.name" >
								<div style="width: 1px;height: 10px;background-color: #cccccc;float: left;margin-top: 7px;padding: 0;margin-right: 5px;"></div>
								<el-button link plain type="primary" @click="submit" :loading="loading" style="float: left;margin-right: 5px;">提交</el-button>
							</template>
						</template>
						<template v-if="form.name">
							<div v-if="form._submitFlag===true" style="width: 1px;height: 10px;background-color: #cccccc;float: left;margin-top: 7px;padding: 0;margin-right: 5px;"></div>
							<el-button link plain type="primary" @click="exportDocument" :loading="exportLoading" style="float: left;margin-right: 5px;">导出</el-button>
							<template v-if="templateUrl">
								<div style="width: 1px;height: 10px;background-color: #cccccc;float: left;margin-top: 7px;padding: 0;margin-right: 5px;"></div>
								<el-button link plain type="primary" @click="printDocument" :loading="printLoading" style="float: left;margin-right: 5px;">打印</el-button>
							</template>
						</template>
						<!--div style="width: 1px;height: 10px;background-color: #cccccc;float: left;margin-top: 7px;padding: 0;margin-right: 5px;"></div>
						<el-button link plain type="primary" :loading="printLoading" style="float: left;">帮助</el-button-->
					</div>
				</div>
			</template>
			<template v-if="this.card" #default>
				<card-content ref="cardContent" :card="card" :data-form="form" :classname="documentclass"></card-content>
			</template>
		</el-card>

    <data-card ref="dataCard" :add-api="this.$API.asset.documentDetail.add"
               :edit-api="this.$API.asset.documentDetail.edit" :preview="cardPreview" ></data-card>

    <asset-selecter ref="assetSelecter" :ids="assetIds" @success="assetSelectHandler" :processType="this.form.processType"></asset-selecter>
	<oark-selecter ref="oarkSelecter" :details="addDetails" @success="oarkSelectHandler"></oark-selecter>
	</el-main>

	<import-asset ref="importAsset" @success="importFinishHandler"></import-asset>
	<import-image ref="importImage" @success="importFinishHandler"></import-image>

	<print-review ref="printReview"></print-review>

<ex-dialog v-model="pjrkChooseDialog" title="配件来源" :width="300" :top="300">
  <template #default>
      <div style="margin-left: 50px;margin-top:10px;margin-bottom: 10px;">
        <el-radio-group v-model="pjrkChooseResult">
          <el-radio label="hand">手工入库</el-radio>
          <el-radio label="OARK">OA入库</el-radio>
          <el-radio label="HTRK">合同入库</el-radio>
          <el-radio label="CJRK">集采入库</el-radio>
        </el-radio-group>
      </div>
  </template>
  <template #footer>
    <el-button @click="pjrkChooseDialogCancel">取消</el-button>
    <el-button type="primary" @click="pjrkChooseDialogConfirm">确定</el-button>
  </template>
</ex-dialog>

</template>

<script>
import scIconSelect from '@/components/scIconSelect'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExLabel from "@/components/exLabel/index.vue";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExTable from "@/components/exTable/index.vue";
import CardContent from "@/views/asset/card/card_content.vue";
import DataCard from "@/views/asset/card/card.vue";
import useTabs from "@/utils/useTabs";
import {DOCUMENT_STATUS} from "@/utils/StaticConstant";
import AssetSelecter from "@/views/asset/asset/asset-selecter.vue";
import FlowApi from "@/api/flowable/FlowApi";
import ImportAsset from "@/views/asset/document/importAsset.vue";
import ImportImage from "@/views/asset/document/importImage.vue";
import globalparam from "@/constant/model/globalparam";
import PrintReview from "@/views/asset/labelPrint/printReview.vue";
import OarkSelecter from "@/views/asset/document/oark-selecter.vue";
import ExDialog from "@/components/exDialog/index.vue";

export default {
	name: '',
	computed: {
    DOCUMENT_STATUS() {
      return DOCUMENT_STATUS
    }
  },
	emits: ['success'],
	components: {
    ExDialog,
		OarkSelecter,
		PrintReview,
		ImportAsset,
		ImportImage,
    	AssetSelecter,
		DataCard,
		CardContent,
		ExTable,
		ExFormItem,
		ExLabel,
		ExRelTable,
		scIconSelect
	},
	props: {},
	data() {
		return {
			isAlready: false,
      pjrkChooseDialog:false,
      pjrkChooseResult:null,
			editProcessType: false,
			click: this.$store.state.click,
			form: {},
			card: null,
			loading: false,
			exportLoading: false,
			printLoading: false,
			documentConfig: null,
			processType: null,
			processTypes: [],
			cardPreview:false,
      		assetIds:[],
      		addDetails:[],
      		currentEditDetail: null,
      		configName:null,
			templateUrl:null,
			loginUser: this.$TOOL.current.user(),
			documentclass:"documentDetail",
		}
	},
	watch: {
		click: {
			async handler(val) {
				let clickState = val[this.form.id]
				if (clickState && clickState.click) {
					await this.$options.methods[clickState.method](this, clickState.data);
					this.$store.dispatch("clearClick", this.form.id);
				}
			},
			deep: true,
			immediate: false,
		},
    form:{
      async handler(val) {
        if(this.form._canReject===false){
          this.form._canReject = await this.auditCheck();
          if(this.form._canReject===false){
            delete this.form._canReject;
          }
        }
      },
      deep: true,
      immediate: false,
    },
    currentEditDetail:{
      handler(val,oldVal) {
        //更新变更信息
        this.refreshChangeInfo();
      },
      deep: true,
      immediate: true,
    }
	},
	async created() {
		//加载单据配置名称
		this.configName = await this.$cache.dic.label('FamsDocumentConfig', this.$route.params.configId);
		//加载单据打印模板
		let minioServerUrl = await this.$cache.data.loadGlobalParam(globalparam.minioServerUrlInner.paramCode);
		let paramValue = await this.$cache.data.loadGlobalParam(globalparam.documentPrintTemplate.paramCode);
		if (paramValue&&paramValue[this.$route.params.configId]) {
			let tempFiles = this.$TOOL.toObj(paramValue[this.$route.params.configId]);
			if (tempFiles[0]) {
				this.templateUrl = minioServerUrl + tempFiles[0].realUrl;
			}
		}
	},
	async mounted() {
		if (this.$route.params.id) {
			await this.initDocument(this.$route.params.id);
		} else {
			await this.initData();
		}
	},
	onLoad() {
	},
	methods: {
    refreshChangeInfo(){

      if(this.currentEditDetail){
        if(!this.currentEditDetail.originalAssetInfo){
          this.currentEditDetail.originalAssetInfo={};
        }
        if(!this.currentEditDetail.assetInfo){
          this.currentEditDetail.assetInfo={};
        }
        if(!this.currentEditDetail.other){
          this.currentEditDetail.other = {};
        }
        let originalAssetInfo = this.$TOOL.objCopy(this.currentEditDetail.originalAssetInfo);
        let assetInfo = this.$TOOL.objCopy(this.currentEditDetail.assetInfo);
        let other = this.$TOOL.objCopy(this.currentEditDetail.other);
        if(other){
          let assetOther =null;
          if(assetInfo.other){
            assetOther = this.$TOOL.objCopy(assetInfo.other);
          }
          Object.assign(assetInfo,other)

          if(other.other){
            if(!assetOther){
              assetOther={}
            }
            Object.assign(assetOther,other.other);
            assetInfo.other = assetOther;
          }
        }
        let currentChangeInfo = {};
        this.parseChangeInfo(currentChangeInfo,originalAssetInfo,assetInfo,'');
        let copyCurrentChangeInfo = this.$TOOL.objCopy(currentChangeInfo);
        if(JSON.stringify(copyCurrentChangeInfo)!==JSON.stringify(this.currentEditDetail.changeInfo)){
          this.currentEditDetail.changeInfo = copyCurrentChangeInfo;
          console.log('changeInfo',this.currentEditDetail.changeInfo);
        }
      }
    },
    parseChangeInfo(currentChangeInfo,original,change,parentProp){
        for (let prop in change){
          if(!prop.startsWith("_")){
            if((change[prop] instanceof Object)&&!Array.isArray(change[prop])){
              if(original[prop]){
                this.parseChangeInfo(currentChangeInfo,original[prop],change[prop],prop+".")
              }else{
                this.parseChangeInfo(currentChangeInfo, {},change[prop],prop+".")
              }
            }else{
              if((change[prop]||original[prop])&&change[prop]!==original[prop]){
                currentChangeInfo[parentProp+prop]={before:original[prop],after:change[prop]};
              }
            }
          }
        }
    },
		async addDocument(addName) {
			if (!this.form.processTypeId) {
				this.$message.error("请选择单据处理方式");
				return false;
			}
			this.loading = true;
			if(addName){
				//设置单据名称
				this.form.name = this.form.name||await this.$cache.dic.label('FamsDocumentConfig', this.$route.params.configId);
			}
			let rsp = await this.$API.asset.document.add.post(this.form);
			if (rsp.code === 2000) {
				this.form = rsp.data;
				this.editProcessType = false;
				this.closePage();
				this.$router.replace(this.$route.fullPath+"/"+this.form.id);
				// await this.initDocument(this.form.id);
			}
			this.loading = false;
		},
    async changeProcessType() {
      await this.saveDocument();
    },
		async saveDocument() {
      if(!this.form.processTypeId){
        this.$message.error("请选择单据处理方式");
        return;
      }
      if (this.form.name!=null) {
        let valid = await this.$refs.cardContent.validate();
        if (!valid) return;
      }

      let confirm = await this.$confirm('是否保存单据信息', '提示', {type: 'warning',confirmButtonText: '是', cancelButtonText: '否'}).then(() => {return true;}).catch(() => {return false;});
      if (!confirm) return;

      try {
        this.loading = true;
        //设置单据名称
        this.form.name = this.form.name||this.configName;

        let rsp = await this.$API.asset.document.edit.post(this.form);
        if (rsp.code === 2000) {
          this.$message.success("保存成功");
          useTabs.refresh();
		      useTabs.refreshDocumentInfo();
        }
      } finally {
        this.loading = false
      }
		},
		async initData() {
			if (!this.form.id) {
				this.form.documentConfigId = this.$route.params.configId;
				this.form.createOrganizationId = this.$TOOL.current.user().orgId;
        await this.myProcessTypes();
			}else{
        await this.myProcessTypes();
        await this.initPage();
      }
			this.documentConfig = await this.$cache.data.loadDocumentConfig(this.$route.params.configId);
			if(this.documentConfig){
				this.form.documentType = this.documentConfig.type;
			}
			this.isAlready = true;
		},
		async initDocument(id) {
			let rsp = await this.$API.asset.document.findById.post({id: id});
			if (rsp.code === 2000) {
				this.form = rsp.data;
				useTabs.setTitle(this.form.code);
				this.form._editFlag = this.$TOOL.current.user().id === this.form.createUser && (this.form.status === DOCUMENT_STATUS.PREPARING);
				console.log(this.form.other.submitStatus)
				this.form._submitFlag = this.$TOOL.current.user().id === this.form.createUser && (this.form.status === DOCUMENT_STATUS.PREPARING)&&(!this.form.other.submitStatus);
				await this.initData();
			}
		},
		async initPage() {
			//获取处理方式对应的审批流程Id
			this.form.flowId = this.form.processType.flowId;
			//读取处理方式对应的卡片
			this.card = await this.$cache.data.loadDataCard(this.form.processType.documentCardId);

			if(this.$TOOL.current.user().id === this.form.createUser && (this.form.status === DOCUMENT_STATUS.PREPARING)){
				//不做权限控制
			}else{
				let btnAuth={showAsset:true};
				this.form._btnAuth = btnAuth;
			}
			//审核中时查询节点的编辑权限
			if(this.form.status===DOCUMENT_STATUS.REVIEW){
				let btnAuth={showAsset:true};
				if(this.form.flowInstanceId){
					let res = await FlowApi.getFlowInsts({ flowInstId: this.form.flowInstanceId});
					if(res.code===2000){
						let flowInst = res.data;
						if(flowInst&&flowInst.buttonPermission){
							let buttonPermission = JSON.parse(flowInst.buttonPermission);
							if(buttonPermission.changeDetails===true){//允许编辑
								btnAuth.editAsset = {cardId:buttonPermission.detailsCardOption};
							}
							if(buttonPermission.bulkEdit===true){//允许批量
								btnAuth.editAssets = {cardId:buttonPermission.bulkCardOption};
							}
							if(buttonPermission.uploadAttachments===true){//必须上传附件
								btnAuth.uploadAttachments = true;
							}
						}
					}
				}
				this.form._btnAuth = btnAuth;
			}
		},
		async myProcessTypes() {
			//读取单据配置信息
			let rsp = await this.$API.asset.processType.myProcessTypes.post({configId: this.form.documentConfigId});
			if (rsp.code === 2000) {
				this.processTypes = this.$cache.dic.toOptions(rsp.data, true);
				this.form._processTypes = this.processTypes;
        if(!this.form.id){
          if (this.processTypes.length === 0) {
            this.$message.warning("未读取到单据处理方式");
            this.closePage();
          } else {
            this.form.processTypeId = this.processTypes[0].value;
            await this.addDocument(this.processTypes.length===1);
          }
        }else{
          if(this.processTypes.length>1){
            if(!this.form.name){
              this.form.processTypeId = null;
              this.editProcessType = true;
            }
          }
        }

			}
		},

		reset() {
			this.form = Object.assign({}, this.oldForm);
			for(let ref in this.$refs){
				try {
					this.$refs[ref].refresh();
				}catch (e){
				}
			}
		},
		//保存
		async submit() {
      try {
        this.loading = true
        if(!this.form.processTypeId){
          this.$message.error("请选择单据处理方式");
          return;
        }

        let valid = await this.auditCheck();
        if (!valid) return;

        let confirm = await this.$confirm('是否提交单据信息', '提示', {type: 'warning',confirmButtonText: '是', cancelButtonText: '否'}).then(() => {return true;}).catch(() => {return false;});
        if (!confirm) return;
		  var res = null;
		if(this.form.other&&this.form.other.submitStatus === true){
			res = await this.$API.asset.document.reSubmit.post(this.form);
		}else{
			res = await this.$API.asset.document.submit.post(this.form)
		}

        if (res.code === 2000) {
          this.$message.success(this.$t("code." + res.code));
          this.$store.dispatch("commit", this.form.entityName);
          useTabs.refresh();
		  useTabs.refreshDocumentInfo();
        } else {
          this.$message.warning(res.message)
        }
      } finally {
        this.loading = false
      }

		},
		//保存
		closePage() {
			try {
				this.loading = true
				useTabs.close();
			} finally {
				this.loading = false
			}
		},
		async assetSelectHandler() {
		  let documentDetail = {documentId: this.form.id, assetIds: this.assetIds,modelId: this.form.id};
		  let rsp = await this.$API.asset.documentDetail.add.post(documentDetail);
		  if(rsp.code===2000){
			this.$message.success(this.$t("code." + rsp.code));
			this.$store.dispatch("commit", this.form.entityName);
			this.$store.dispatch("refreshClick", this.form.id);
		  }
		},
		async oarkSelectHandler() {
			this.addDetails.forEach(addDetail=>{
				addDetail.documentId = this.form.id;
			});

			let rsp = await this.$API.asset.documentDetail.addDetails.post(this.addDetails);
			if(rsp.code===2000){
				this.$message.success(this.$t("code." + rsp.code));
				this.$store.dispatch("commit", this.form.entityName);
				this.$store.dispatch("refreshClick", this.form.id);
			}
		},
		async importFinishHandler() {
			this.$store.dispatch("refreshClick", this.form.id);
		},
		//获取可操作的资产类别
		currentAssetCategoryIds(_this){
			let assetCategoryIds = _this.form.processType.assetCategoryIds;
			let roleManageAssetCategoryIds = _this.$TOOL.current.manageAssetCategoryIds();
			//如果当前角色有管理资产类别限制，单据也有管理资产类别限制，则取两者的交集，否则直接使用单据的资产类别限制
			let realAssetCategoryIds = {};
			if(roleManageAssetCategoryIds && assetCategoryIds){
				if(Array.isArray(roleManageAssetCategoryIds)){
					roleManageAssetCategoryIds.forEach(item=>{
						realAssetCategoryIds[item] = true;
					});
				}
				if(Array.isArray(assetCategoryIds)) {
					for (let item in realAssetCategoryIds){
						if(!assetCategoryIds.includes(item)){
							delete realAssetCategoryIds[item];
						}
					}
				}
				assetCategoryIds = [];
				for (let item in realAssetCategoryIds){
					assetCategoryIds.push(item);
				}
			}
			return assetCategoryIds;
		},
    pjrkChooseDialogCancel(){
      this.pjrkChooseResult = null;
      this.pjrkChooseDialog = false;
    },
    pjrkChooseDialogConfirm(){
      if(this.pjrkChooseResult == null){
        return;
      }
      this.pjrkChooseDialog = false;
      this.addAsset(this);
    },
		//添加
		async addAsset(_this, data) {
      if (_this.form.name==null) {
		  await _this.saveDocument();
		  // _this.$message.error("请选择单据处理方式,并保存单据信息");
		  return;
      }

      let valid = await _this.$refs.cardContent.validate();
      if (!valid) return;

      let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);
      if(documentConfig.type==='in'){//为入库时
        try {
          _this.loading = true;
          _this.pjrkChooseDialog = false;
		 // console.log(_this.form)
          //如果是配件入库，需要选择手工入库还是接口入库
          if(_this.form.processType.code==='PJRK'&&_this.pjrkChooseResult == null){
            _this.pjrkChooseResult = null;
            _this.pjrkChooseDialog = true;
            return true;
          }
          if(_this.pjrkChooseResult==='OARK'||_this.pjrkChooseResult==='CJRK'||_this.pjrkChooseResult==='HTRK'){
            let batchType = _this.pjrkChooseResult;
            _this.$nextTick(() => {
              _this.$refs.oarkSelecter.open({batchType:batchType});
            });
          }else if(_this.form.processType.code==='OARK'||_this.form.processType.code==='CJRK'||_this.form.processType.code==='HTRK'){
			  _this.$nextTick(() => {
				  _this.$refs.oarkSelecter.open({batchType:_this.form.processType.code});
			  });
		  }else{
			  let documentDetail = {documentId: _this.form.id, assetInfo: {}};
			  let entity = {modelId: _this.form.id, cardId: _this.form.processType.addCardId,_editFlag:true,assetCategoryIds:_this.currentAssetCategoryIds(_this)}

			  _this.$nextTick(() => {
				  _this.cardPreview = false;
				  _this.currentEditDetail = _this.$TOOL.objCopy(Object.assign(entity, documentDetail));
				  _this.$refs.dataCard.open(_this.currentEditDetail);
			  });
		  }
        }finally {
          _this.pjrkChooseResult = null;
          _this.loading = false;
        }
      }else if(documentConfig.type==='permission'){//为权限管理时
		  try {
			  _this.loading = true;
			  let queryParams = {};
			  queryParams.createUser = _this.loginUser.id;
			  queryParams.excludeDocumentStatus = ['nopass','executed','cancel','preparing'];
			  _this.$API.asset.document.listOwnApplyOverTimeOrApproveDocumentIds.post(queryParams).then(rsp => {
				  if (rsp.code == 2000) {
					  if (rsp.data && rsp.data.length > 0) {
						  _this.$message.error("当前有待审批的单据，请先完成任务再进行操作");
						  return;
					  }
				  }
				  let documentDetail = {documentId: _this.form.id, assetInfo: {}};
				  let entity = {modelId: _this.form.id, cardId: _this.form.processType.addCardId,_editFlag:true}

				  _this.$nextTick(() => {
					  _this.cardPreview = false;
					  _this.currentEditDetail = _this.$TOOL.objCopy(Object.assign(entity, documentDetail));
					  _this.$refs.dataCard.open(_this.currentEditDetail);
				  });
			  });
		  }finally {
			  _this.loading = false;
		  }
	  }else{//其它为变动

		  _this.$message.warning("提示：若选择的资产包含配件或为配件且已绑定，那么相关联的资产将被自动添加到单据明细内，请知晓!");

        _this.$nextTick(async () => {
          _this.assetIds = [];
          let queryParams = {
            // isLocked:'0',//获取所有资产，对于锁定的不可勾选
            assetStatisticsRange: "2",//资产选择范围为使用部门在管理范围之内的
            assetCategoryIds: _this.currentAssetCategoryIds(_this),
            assetStatusIds: _this.form.processType.assetStatusIds,
            financialTypes: _this.form.processType.financialTypes,
            deptIds: _this.$TOOL.current.manageDeptIds(),
            isIncludeCheckAsset: _this.form.processType.isIncludeCheckAsset === '1', //是否可以选择盘点中的资产
            documentType: documentConfig.type,
            processTypeCode: _this.form.processType.code,
          };

         // console.log(_this.form.processType)
          if (_this.form.processType.isIncludeCheckAsset === '0') {
            //queryParams.isTask=0;//设置查询未在盘点任务中的资产，暂时不过滤，根据是否允许操作盘点中资产设置不可勾选
          }
          _this.$refs.assetSelecter.open(queryParams);
        })
      }
      return true;
		},
		//编辑
		async editAsset(_this, data) {
			let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);
			if(documentConfig.type!=='permission'&&documentConfig.type!=='in'&&documentConfig.type!=='scrap'){
				if(data.assetId){
					_this.$message.warning("提示：若操作的资产包含配件或为配件且已绑定，那么相关联的资产将会同步编辑，请知晓!");
				}
			}

      try {
        _this.loading = true;
		//获取编码卡片id
        let editCardId = _this.form.processType.editCardId;
        if(_this.form._btnAuth){
          if(_this.form._btnAuth.editAsset){
            editCardId = _this.form._btnAuth.editAsset.cardId||editCardId;
          }
        }

        let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);

        let entity = {modelId: _this.form.id, cardId: editCardId,_editFlag:true,assetCategoryIds:_this.currentAssetCategoryIds(_this),documentType:documentConfig.type};
        _this.$nextTick(() => {
          _this.cardPreview = false;
          _this.currentEditDetail = _this.$TOOL.objCopy(Object.assign(entity, data));
          _this.$refs.dataCard.open(_this.currentEditDetail);
        });
      }finally {
        _this.loading = false;
      }
			return true;
		},
		//编辑
		async editAssets(_this, _data) {

			let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);
			if(documentConfig.type!=='permission'&&documentConfig.type!=='in'&&documentConfig.type!=='scrap'){
				if(_data.selections[0].assetId){
					_this.$message.warning("提示：若操作的资产包含配件或为配件且已绑定，那么相关联的资产将会同步编辑，请知晓!");
				}
			}


			try {
				_this.loading = true;
				let data = _this.$TOOL.objCopy(_data);
				//获取编码卡片id
				let editCardId =  _this.form.processType.editsCardId;
				if(_this.form._btnAuth){
					if(_this.form._btnAuth.editAssets){
						editCardId = _this.form._btnAuth.editAssets.cardId||editCardId;
					}
				}

				let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);

				let entity = {modelId: _this.form.id, cardId: editCardId,_editFlag:true,assetCategoryIds:_this.currentAssetCategoryIds(_this),documentType:documentConfig.type};
				_this.$nextTick(() => {
					_this.cardPreview = false;
					let detailData =  data.selections[0];
					let detailIds = [];
					if(data.type==='select'){
						data.selections.forEach(row=>{
							detailIds.push(row.id);
						});
					}
					detailData.detailIds = detailIds;
					_this.currentEditDetail = _this.$TOOL.objCopy(Object.assign(entity, detailData));
					_this.currentEditDetail._editAssets = true;
					_this.$refs.dataCard.open(_this.currentEditDetail);
				});
			}finally {
				_this.loading = false;
			}
			return true;
		},
		//标签打印
		labelPrint(_this, data) {
			let selections = data.selections;
			if (selections.length === 0) {
				_this.$message.warning(_this.$t("common.please_select_data"));
				return;
			}
			_this.$confirm(`确定打印选择的 ${selections.length} 项吗？`, '警告', {
				type: 'warning'
			}).then(async () => {
				_this.loading = true;
				let assetCodes = [];
				let documentId = null;
				for (let index = 0; index < selections.length; index++) {
					const element = selections[index];
					assetCodes.push(element.assetInfo.code);
					documentId = element.documentId;
				}

				let data = {
					assetCodes:assetCodes,
					documentId:documentId,
				};
				_this.$nextTick(() => {
					_this.$refs.printReview.open(data);
				})
				_this.loading = false;
			}).catch(() => {
				_this.loading = false;
			});
		},
		async importAssets(_this, data) {

			if (_this.form.name==null) {
				await _this.saveDocument();
				// _this.$message.error("请选择单据处理方式,并保存单据信息");
				return;
			}

			let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);
			if(documentConfig.type!=='permission'&&documentConfig.type!=='in'){
				_this.$message.warning("提示：若导入的资产包含配件或为配件且已绑定，那么相关联的资产将会一起导入到单据明细，请知晓!");
			}

			let entity = {
				documentId:_this.form.id,
				documentConfigId: _this.form.documentConfigId,
				assetCategoryIds:_this.currentAssetCategoryIds(_this),
				assetStatusIds:_this.form.processType.assetStatusIds,
				isIncludeCheckAsset:_this.form.processType.isIncludeCheckAsset,
				documentType:documentConfig.type,
				financialTypes: _this.form.processType.financialTypes,
				processTypeCode: _this.form.processType.code,
			};
			_this.$nextTick(() => {
			_this.$refs.importAsset.open(entity);
			});
			return true;
		},
		async importImage(_this) {

			if (_this.form.name==null) {
				await _this.saveDocument();
				// _this.$message.error("请选择单据处理方式,并保存单据信息");
				return;
			}

			let documentConfig = await _this.$cache.data.loadDocumentConfig(_this.form.documentConfigId);
			if(documentConfig.type!=='permission'&&documentConfig.type!=='in'){
				_this.$message.warning("提示：若导入的资产包含配件或为配件且已绑定，那么相关联的资产将会一起导入到单据明细，请知晓!");
			}

			let entity = {
				documentId:_this.form.id,
				documentCode:_this.form.code,
				documentConfigId: _this.form.documentConfigId,
				assetCategoryIds:_this.currentAssetCategoryIds(_this),
				assetStatusIds:_this.form.processType.assetStatusIds,
				isIncludeCheckAsset:_this.form.processType.isIncludeCheckAsset,
				documentType:documentConfig.type,
				financialTypes: _this.form.processType.financialTypes,
				processTypeCode: _this.form.processType.code,
			};
			_this.$nextTick(() => {
			_this.$refs.importImage.open(entity);
			});
			return true;
		},
		//查看
		async showAsset(_this, data) {
      try {
        _this.loading = true;
        let entity = {modelId: _this.form.id, cardId: _this.form.processType.showCardId,_editFlag:false}
        _this.$nextTick(() => {
          _this.cardPreview = true;
          _this.$refs.dataCard.open(Object.assign(entity, data));
        });
      }finally {
        _this.loading = false;
      }
			return true;
		},

		//导出单据
		async exportDocument() {
			let confirm = await this.$confirm('是否导出?', '提示', {type: 'warning',confirmButtonText: '是', cancelButtonText: '否'}).then(() => {return true;}).catch(() => {return false;});
			if (!confirm) return;
			try {
				this.exportLoading = true

				let widgetColumns = [];
				if(this.card&&this.card.modules){
					this.card.modules.forEach(module=>{
						if(module.widgets){
							module.widgets.forEach(widget=>{
								if(widget.props.type==='dy-table'&&widget.props.columns){
									widgetColumns = widget.props.columns;
								}
							})
						}
					});
				}
				let columns = [];
				if(widgetColumns){
					widgetColumns.forEach(item=>{
						if(!item.fixedValue){
							let column = {
								property:item.property,
								label:item.label||item.name,
								formatter:item.formatter,
								key:item.key
							}
							columns.push(column);
						}
					});
				}
				let queryPrams = {
					exportType:"documentDetailExport",
					exportName:this.form.name+"["+this.form.code+"]",
					documentId:this.form.id,
					exportColumns:columns,
				};

				let res = await this.$API.asset.documentDetail.export.post(queryPrams);
				if (res.code === 2000) {
					await this.$alert(this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
				}
			}finally {
				this.exportLoading = false
			}
		},
		//打印单据
		async printDocument() {

			try {
				this.printLoading = true;
				if (!this.templateUrl) {
					this.$message.error("未配置打印模板,请联系管理员处理");
					return;
				}
        let confirm = await this.$confirm('是否打印单据?', '提示', {type: 'warning',confirmButtonText: '是', cancelButtonText: '否'}).then(() => {return true;}).catch(() => {return false;});
        if (!confirm) return;

				let data = {
					reportType: "pdf",// html,pdf
					templateUrl: this.templateUrl,
					documentId: this.form.id,
				};
				let res = await this.$API.system.jasper.documentPrint.post(data);
				let blob = null;
				if (data.reportType === 'html') {
					blob = new Blob([res], {type: 'text/html'}); //文件流处理
				} else {
					blob = new Blob([res], {type: 'application/pdf'}); //文件流处理
				}
				this.pdfUrl = window.URL.createObjectURL(blob);
				window.open(this.pdfUrl);
			} finally {
				this.printLoading = false;
			}

		},

    async auditCheck() {
      let valid = await this.$refs.cardContent.validate();
      if (!valid) return false;
		//保存一次单据信息
		try {
			let rsp = await this.$API.asset.document.edit.post(this.form);
			if(rsp.code!==2000){
				return false;
			}
		} catch (e){
			this.$message.error("单据保存失败");
			return false;
		}

      let needCheckDetail = true;
      if(this.form.status===DOCUMENT_STATUS.PREPARING){
        needCheckDetail=true;
      }else{
        needCheckDetail = false;
        if(this.form._btnAuth){
          needCheckDetail = !!this.form._btnAuth.editAsset;
        }
      }
      if(!needCheckDetail){
        return  true;
      }
      let rsp = await this.$API.asset.document.findById.post({id: this.form.id});
      if (rsp.code === 2000) {
        let document = rsp.data;
        if(document.other){
          if(!document.other.detailOrderWeight||document.other.detailOrderWeight===0){
            valid = false;
          }
        }else{
          valid = false;
        }
        if(!valid){
          this.$message.error("提交失败，请校验单据明细信息是否填写完整");
          return false;
        }
      }else{
          return false;
      }
      return true;
    }
	}
}
</script>

<style scoped>
h2 {
	font-size: 17px;
	color: #3c4a54;
	padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
	color: #fff;
}
.submit-actions{
	position: fixed;
    bottom: 10px;
    width: 78%;
    height: 50px;
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    z-index: 999;
	text-align: center;
}

::v-deep.documentDetail .showModuleClass  .is-never-shadow{
	margin:-10px -5px 0px !important
}

/*
::v-deep.documentDetail .showModuleClass  .is-never-shadow .el-tabs__header{
	margin: 0px 5px 5px;
}
*/
::v-deep.documentall{
	padding-bottom: 10px;
}
</style>
